package models

import (
	"encoding/json"
	"fmt"
	"gitee.com/tsingeye/FreeEhome/config"
	"gitee.com/tsingeye/FreeEhome/service/ehome/udp"
	"gitee.com/tsingeye/FreeEhome/tools/logs"
	"gitee.com/tsingeye/FreeEhome/tools/sqlDB"
	"strconv"
	"strings"
	"time"
)

//查询设备列表
func DeviceList(status string, page, limit int) (replyData map[string]interface{}) {
	deviceList := make([]sqlDB.DeviceTable, 0)
	offset := (page - 1) * limit
	var totalCount int64

	switch status {
	case "ON", "OFF":
		if err := sqlDB.PagingQuery(&deviceList, limit, offset, "status = ?", status); err != nil {
			logs.BeeLogger.Error("DeviceController.AppointOnDutyList() ---> sqlDB.PagingQuery(&sqlDB.DeviceTable{}) error:%s", err)
			return
		}
		totalCount = sqlDB.Count(&sqlDB.DeviceTable{}, "status = ?", status)
	default:
		if err := sqlDB.PagingQuery(&deviceList, limit, offset); err != nil {
			logs.BeeLogger.Error("DeviceController.AppointOnDutyList() ---> sqlDB.PagingQuery(&sqlDB.DeviceTable{}) error:%s", err)
			return
		}
		totalCount = sqlDB.Count(&sqlDB.DeviceTable{}, "")
	}

	replyData = map[string]interface{}{
		"errCode":    config.EHomeSuccessOK,
		"errMsg":     config.HTTPCodeMap[config.EHomeSuccessOK],
		"totalCount": totalCount,
		"deviceList": deviceList,
	}
	return
}

//查询指定设备下的通道列表
func ChannelList(deviceID, status string, page, limit int) (replyData map[string]interface{}) {
	channelList := make([]sqlDB.ChannelTable, 0)
	offset := (page - 1) * limit
	var totalCount int64

	switch status {
	case "ON", "OFF":
		if err := sqlDB.PagingQuery(&channelList, limit, offset, "deviceID = ? AND status = ?", deviceID, status); err != nil {
			logs.BeeLogger.Error("DeviceController.ChannelList() ---> sqlDB.PagingQuery(&sqlDB.ChannelList{}) error:%s", err)
			return
		}
		totalCount = sqlDB.Count(&sqlDB.ChannelTable{}, "deviceID = ? AND status = ?", deviceID, status)
	default:
		if err := sqlDB.PagingQuery(&channelList, limit, offset, "deviceID = ?", deviceID); err != nil {
			logs.BeeLogger.Error("DeviceController.ChannelList() ---> sqlDB.PagingQuery(&sqlDB.ChannelList{}) error:%s", err)
			return
		}
		totalCount = sqlDB.Count(&sqlDB.ChannelTable{}, "deviceID = ?", deviceID)
	}

	replyData = map[string]interface{}{
		"errCode":     config.EHomeSuccessOK,
		"errMsg":      config.HTTPCodeMap[config.EHomeSuccessOK],
		"totalCount":  totalCount,
		"channelList": channelList,
	}
	return
}

//解析更细通道信息
type parseUpdateChannel struct {
	ChannelAlias string `json:"channelAlias"` //通道别名
}

//更新通道信息
func UpdateChannel(channelID string, requestBody []byte, remoteAddr string) (replyData map[string]interface{}) {
	var updateChannel parseUpdateChannel
	if err := json.Unmarshal(requestBody, &updateChannel); err != nil {
		logs.BeeLogger.Error("DeviceController.UpdateChannel() ---> remoteAddr=%s, requestBody=%s, channelID=%s, json.Unmarshal() error:%s", remoteAddr, requestBody, channelID, err)

		replyData = map[string]interface{}{
			"errCode": config.EHomeClientBadRequest,
			"errMsg":  config.HTTPCodeMap[config.EHomeClientBadRequest],
		}
		return
	}
	fmt.Println(updateChannel.ChannelAlias+"11111")

	//if err := sqlDB.UpdatesMultipleColumns(&sqlDB.ChannelTable{ChannelID: channelID}, map[string]interface{}{"ChannelID": channelID,"channelAlias": updateChannel.ChannelAlias, "updatedAt": time.Now().Format(config.TimeLayout)}, true); err != nil {
	if err := sqlDB.UpdatesMultipleColumns(sqlDB.ChannelTable{ChannelID: channelID}, map[string]interface{}{"channelAlias": updateChannel.ChannelAlias, "updatedAt": time.Now().Format(config.TimeLayout)}, true); err != nil {
		//SQL语句出错，默认更新通道失败
		logs.BeeLogger.Error("DeviceController.UpdateChannel() ---> remoteAddr=%s, requestBody=%s, update channelID=%s failed, error:%s", remoteAddr, requestBody, channelID, err)

		replyData = map[string]interface{}{
			"errCode": config.EHomeServerError,
			"errMsg":  config.HTTPCodeMap[config.EHomeServerError],
		}
		return
	}

	//更新通道成功
	logs.BeeLogger.Emergency("DeviceController.UpdateChannel() ---> remoteAddr=%s, update channelID=%s successfully!!!", remoteAddr, channelID)

	replyData = map[string]interface{}{
		"errCode": config.EHomeSuccessOK,
		"errMsg":  config.HTTPCodeMap[config.EHomeSuccessOK],
	}
	return
}

//云台控制
func PtzControl(channelID, ptzCmd, action string, speed int64) (replyData map[string]interface{}) {
	strList := strings.Split(channelID, "_")
	if len(strList) != 2 {
		logs.BeeLogger.Warn("DeviceController.PtzControl() ---> channelID=%s, channelID format error!!!", channelID)
		return
	}

	realChannelID, err := strconv.ParseInt(strList[1], 0, 64)
	if err != nil {
		logs.BeeLogger.Warn("RecordController.QueryRecordedFiles() ---> channelID=%s, channelID format error!!!", channelID)
		return
	}

	var channelData sqlDB.ChannelTable
	if err := sqlDB.First(&channelData, "channelID = ?", channelID); err != nil {
		logs.BeeLogger.Error("RecordController.QueryRecordedFiles() ---> channelID=%s, sqlDB.First(&sqlDB.ChannelTable{}) error:%s", channelID, err)

		replyData = map[string]interface{}{
			"errCode": config.EHomeChannelIDNotFound,
			"errMsg":  config.HTTPCodeMap[config.EHomeChannelIDNotFound],
		}
		return
	}
	return udp.PtzControl(channelData.DeviceID, realChannelID, ptzCmd, action, speed)
}